/**
 * 浦发云账单，抓取
 */
var teskKey;
var timeout = null;
//账单日
var billDay;
var showTimes = 0;
var dataList = new ArrayList()
//点击登录按钮后获取到的页面
var loginHtml;
//是否正确输入
var isInput = false;
var urls = {
    //请求登录页面
    REQ_LOGIN_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/toLogin.action",
    // 请求验证图片验证码
    REQ_IMG_CODE_VALID_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/pictureCode.action",
    // 请求发送短信地址
    REQ_SMS_CODE_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/sendLoginSms.action",
    //登录成功后请求首页地址
    REQ_LOGIN_INDEX_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/loginIndex.action",
    //获取卡号
    REQ_CARD_INFO_LIST_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/queryAccountList.action",
    //
    REQ_ACCOUNT_OR_BILL_DATA_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/myBillController/changeAccountOrBillData.action",
    //请求卡信息页面
    REQ_SHOW_PC_INDEX_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/myBillController/showPcIndex.action",
    //请求已出账单页面
    REQ_LOAD_HOME_DATA_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/myBillController/loadHomeData.action",
    //请求未出账单页面
    REQ_PC_BILL_DETAIL_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/billDetailController/PCbillDetail.action",
    //请求账单明细
    REQ_LOAD_BILLS_DETAILALL_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/billDetailController/PCloadBillsDetailAll.action",
    // 本期，上期还款信息，本期应还款总额= 上期应还款余额- 已还款金额/其他入账+ 新签金额/其他费用
    REQ_PC_LOAD_HOME_DATA_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/billDetailController/PCloadHomeData.action",
    REQ_SHOW_UNBILL_DETAIL_URL:"https://ebill.spdbccc.com.cn/cloudbank-portal/billDetailController/showPCUnBillDetail.action",

}
var v6_spd_credit_java_funcs = {
    openHomePage : function(){
        var loginUrl = urls.REQ_LOGIN_URL;
        var loginText = get(loginUrl);
        var loginIndex = 1;
        do {
            if(loginText.contains("HTTP 400 错误的请求")){
                logger.info("SPD taskKey：{} 第 {} 次重新发起请求 ",context.get(LUA_TASK_KEY),loginIndex);
                loginText = get(loginUrl);
                // 等待三秒钟;
                luaFuncs.threadSleep();
                loginIndex++;
            }
            storeDataToFile(context, loginText, loginIndex + "_login_html.html");
        }while (loginText.contains("HTTP 400 错误的请求") && loginIndex < 10)
        context.put("loginText", loginText);
    },
    checkProxyAvailable : function() {
        var loginText = context.get("loginText");
        //根据返回页面信息判断是不是代理ip异常
        if (loginText.contains("HTTP 400 错误的请求") ) {
            logger.info("SPD taskKey = " + context.get(LUA_TASK_KEY) + " 代理IP异常");
            return false;
        } else {
            return true;
        }
    },
    checkTargetWebsiteAvailable: function(){
        return true;
    },
    /*检查控件是否可用*/
    checkControlAvailable :function () { return true },
    //只有在图片验证码错误或短信验证码错误　　重置环境
    needResetEnvironment :function () {
        return  equals(context.get("currentErrorCode"),BALO_99602_50) || equals(context.get("currentErrorCode"),BALO_99602_40);
    },
    login: function() {
        isLoginSeccess();
        //从选择账号，月份页面跳入账单页面
        jumpToBillHtml();
    },
    crawl : crawl,
    exitLogin :function () {}

}

/**
 * 用户登录
 */
function isLoginSeccess(){
    showTimes = System.nanoTime();   //用来计算窗口show的时间
    var idNoIsExist = is_exist_by_id("idNo");
    if(idNoIsExist){
        logger.info("任务【 {} 】页面加载成功", context.get(LUA_TASK_KEY));
    }else {
        logger.info("任务【 {} 】页面加载失败", context.get(LUA_TASK_KEY));
        throwBankExceptionByErrorCode(BALO_99601_30);
    }
    var idNo = getLoginParams(context)[0];
    //输入图片验证码
    inputIdCard(idNo);
    var imgIndex = 1;
    var isValidImgCode = false;
    do {
        isValidImgCode = false;
        //显示窗口
        luaFuncs.setSizeAndShow();
        // 获取图片验证码
        getImgValidCode();
        //输入图片验证码
        var captcha = inputImgValidCode();
        Thread.sleep(1000);        // 验证图片验证码是否正确
        var imgValidCodeResultUrl = urls.REQ_IMG_CODE_VALID_URL;
        var paramsMap = new HashMap();
        paramsMap.put("idNo", idNo);
        paramsMap.put("idType", "01");
        paramsMap.put("code", captcha);
        paramsMap.put("ptcId", "1");
        logger.info("浦发云账单,任务{} 第{}次发送验证图片验证码是否正确",context.get(LUA_TASK_KEY),imgIndex);
        var  imgCodeHtml = ajax_post(imgValidCodeResultUrl, paramsMap);
        // var  imgCodeHtml = "return is null"; 503 Service Unavailable
        logger.info("浦发云账单,任务{} 第{}次发送验证图片验证码是否正确,请求结果为：{}",context.get(LUA_TASK_KEY),imgIndex,imgCodeHtml);
        if(imgCodeHtml.contains("return is null") || imgCodeHtml.contains("9DhefwqGPrzGxEp9hPaoag") || imgCodeHtml.contains("503 Service Unavailable")){
            logger.info("浦发云账单,任务{} 第{}次发送验证图片验证码错误",context.get(LUA_TASK_KEY),imgIndex);
            break;
        }else{
            if(StringUtils.isNotBlank(imgCodeHtml)){
                var imgCodeJSON = JSON.parse(imgCodeHtml);
                if(imgCodeJSON != undefined){
                    var imgValidResult = imgCodeJSON.get("result");
                    if (StringUtils.isNotBlank(imgValidResult)){
                        if(imgValidResult.equals("Right")){
                            isValidImgCode = true;
                        }
                    }
                }
            }
        }
        if(!isValidImgCode){
            // 点击验证码
            click_by_id("imgObj");
        }
        imgIndex++;
    }while (!isValidImgCode && imgIndex<=4)
    hide();
    //检查验证码是否输入正常
    // var captchaInputResult = luaFuncs.checkIfInput("code", captcha);
    logger.info("isValidImgCode 返回信息"+isValidImgCode);
    var isCaptchaInputCorrectFunc = function(isValidImgCode) {
        return isValidImgCode;
    }
    var getCaptchaInputErrorMsgFunc = function() {
        return "图片验证码错误"
    }
    assertTrueOrThrowException(isValidImgCode, isCaptchaInputCorrectFunc, getCaptchaInputErrorMsgFunc);
    // luaFuncs.mouseMoveClick();
    var smsCodeUrl = urls.REQ_SMS_CODE_URL;
    var paramsMap = new HashMap();
    paramsMap.put("idNo", idNo);
    paramsMap.put("idType", "01");
    paramsMap.put("yzmM", captcha);
    var isSmsFild = false;
    // 因为短信60秒内不能重复发送，这个不需要进行循环
    logger.info("浦发云账单,任务{} 发送短信验证码请求",context.get(LUA_TASK_KEY));
    var smsCodeHtml = luaFuncs.pf_ajax_post(smsCodeUrl, paramsMap, timeout);
    logger.info("浦发云账单,任务{} 发送短信验证码是否正确,返回结果为：{}",context.get(LUA_TASK_KEY),smsCodeHtml);
    if(smsCodeHtml != undefined){
        if(smsCodeHtml.contains("msg")){
            var smsCodeJsoup = JSON.parse(smsCodeHtml);
            logger.info("浦发云账单 taskKey:{} 发送短信是否成功，smsCodeJsoup:{}",context.get(LUA_TASK_KEY),smsCodeJsoup);
            if(smsCodeJsoup != undefined){
                var smsCodeRes = smsCodeJsoup.get("msg");
                if(Boolean.valueOf(smsCodeRes)){
                    isSmsFild = true;
                }else if(equals("yzm60s",smsCodeRes)){
                    isSmsFild = true;
                }else{
                    isSmsFild = false;
                }
            }
        }
    }
    var isSmsSendCorrectFunc = function(isSmsFild) {
        return isSmsFild;
    }
    var getSmsSendErrorMsgFunc = function() {
        return "发送短信失败";
    }
    assertTrueOrThrowException(isSmsFild, isSmsSendCorrectFunc, getSmsSendErrorMsgFunc);
    logger.info("浦发云账单 taskKey:{} 发送短信成功，",context.get(LUA_TASK_KEY));
    showTimes =  System.nanoTime() - showTimes;   //用来计算窗口show的时间
    logger.info("浦发云账单 taskKey:{} 开始等待短信验证码时间{}",context.get(LUA_TASK_KEY),showTimes);
    hide();
    //等待短信
    var smsCode = waitSmsCodeBySeconds(context, 120);
    logger.info("浦发云账单 taskKey:{} 等待短信结果{}",context.get(LUA_TASK_KEY),smsCode);
    //action开始: 校验短信验证码
    var isSmsCodeCorrectFunc = function(smsCode) {
        return StringUtils.isNotBlank(smsCode) && smsCode.length === 6;
    }
    var getSmsCodeErrorMsgFunc = function() {
        return "短信验证码错误";
    }
    assertTrueOrThrowException(smsCode, isSmsCodeCorrectFunc, getSmsCodeErrorMsgFunc);
    showTimes =  System.nanoTime() - showTimes;   //用来计算窗口show的时间
    logger.info("浦发云账单 taskKey:{} 开始等待验证短信验证码结束时间{}",context.get(LUA_TASK_KEY),showTimes);
    //输入短信验证码
    set_input_text_by_id("messagePwd",smsCode);
    //检查短信验证码是否输入正常
    var smsInputResult = luaFuncs.checkIfInput("messagePwd",smsCode);

    var isSmsInputCorrectFunc = function(smsInputResult) {
        return Boolean.valueOf(smsInputResult);
    }

    var getSmsInputErrorMsgFunc = function(smsInputResult) {
        return "短信验证码错误";
    }
    assertTrueOrThrowException(smsInputResult, isSmsInputCorrectFunc, getSmsInputErrorMsgFunc);
    //显示窗口
    luaFuncs.setSizeAndShow();
    luaFuncs.threadSleep();
    //点击登录按钮
    luaFuncs.click_login_button();
    loginHtml = luaFuncs.getHtml2();
    storeDataToFile(context, loginHtml, "loginHtml.html");
    logger.info("浦发云账单 taskKey:{} 登录按钮点击后页面已保存",context.get(LUA_TASK_KEY));
    var doc = Jsoup.parse(loginHtml);
    var isLoginMassge = doc.select("#tipInfo").text();
    var loginFlag = true;
    if(StringUtils.isNotBlank(isLoginMassge)){
        logger.info("浦发云账单 登录信息 tipInfo:{}",isLoginMassge);
        loginFlag=false;
    }
    logger.info("浦发云账单 登录信息 isLoginMassge:{}",isLoginMassge);
    var isLoginCorrectFunc = function() {
        return loginFlag;
    }
    var getLoginErrorMsgFunc = function(loginHtml) {
        if(loginHtml === null) {
            return "短信验证码错误";
        } else if(StringUtils.isNotBlank(isLoginMassge)) {
            return isLoginMassge;
        }
    }
    assertTrueOrThrowException(loginHtml, isLoginCorrectFunc, getLoginErrorMsgFunc);
    hide();
    var accSize = doc.select("#loginAccount option").size() > 1;
    var accMonthSize = doc.select("#loginMonth option").size() > 1;
    logger.info("浦发云账单 taskKey:{} 获取到用户有{} 个账户",context.get(LUA_TASK_KEY),accSize);
    var isLoginCorrectFunc = function(accSize) {
        return accSize;
    }
    var getLoginErrorMsgFunc = function() {
        return "未获取到卡片信息";
    }
    assertTrueOrThrowException(accSize, isLoginCorrectFunc, getLoginErrorMsgFunc);
    //从选择账号，月份页面跳入账单页面
    context.put("login_html",loginHtml);
}

/**
 * 登录页选取账单月和银行卡
 */
function jumpToBillHtml(){
    var monthIndex = 1;
    var allMonthCount = 12;
    //跳转是否成功的标记
    var jumpNotOk;
    do{
        jumpNotOk = false;
        //查看用户是否有卡列表信息
        luaFuncs.selectAccount();
        screen_print();
        // 获取卡列表信息
        crawlCardList();
        //storeDataToFile(context, selectAccountHtml, "selectAccount.html");
        //选取账单月
        luaFuncs.selectBillMonth(Integer.parseInt(monthIndex));
        luaFuncs.jumpToBill();

        //判断是否跳转成功
        jumpNotOk = checkIfJumpSuccess(monthIndex);
        screen_print();
        monthIndex++;
    } while(jumpNotOk);
}

/**
 * 判断是否跳转到首页
 * @param monthIndex
 * @returns {boolean}
 */
function checkIfJumpSuccess(monthIndex){
    var loginHtml2 = luaFuncs.getHtml2();
    storeDataToFile(context, loginHtml2, "loginHtml2_"+monthIndex+".html");
    if(StringUtils.isNotBlank(loginHtml2)){
        var doc = Jsoup.parse(loginHtml2);
        var errorMsg = doc.select("#tipInfo").text();
        logger.info("浦发云账单 taskKey:{} 打印错误提示信息 {}",context.get(LUA_TASK_KEY),errorMsg);
        if(StringUtils.isNotBlank(errorMsg)){
            if(errorMsg.contains("该月账单暂未产生，请选择其他月份！")){
                logger.info("浦发云账单 taskKey:{} 选择第：【{}】个账单月跳转失败,该月账单暂未产生，请选择其他月份！",context.get(LUA_TASK_KEY),monthIndex);
                return true;
            }else if(errorMsg.contains("请选择年月")){
                logger.info("浦发云账单 taskKey:{} 选择第：【{}】个账单月跳转失败,该月账单暂未产生，请选择年月",context.get(LUA_TASK_KEY),monthIndex);
                return true;
            }else if(errorMsg.contains("请选择账户号")){
                luaFuncs.closeErrorMsgButton();
                logger.info("浦发云账单 taskKey:{} 未选择账户号,请选择账户号",context.get(LUA_TASK_KEY));
                return true;
            }else{
                logger.error("浦发云账单 taskKey:{} 检查跳转账单页结果时发现新分支,{}",context.get(LUA_TASK_KEY), errorMsg);
                throw new BankException(BALO_23001_10,"检查跳转账单页结果时发现新分支");
            }
        }else {
            logger.info("浦发云账单 taskKey:{} 跳转到账单详情页面未获取到错误信息，跳转成功！",context.get(LUA_TASK_KEY));
            return false;
        }
    }else {
        logger.info("浦发云账单 taskKey:{} 跳转到账单详情页面为空:{}",context.get(LUA_TASK_KEY),loginHtml2);
        throw new BankException(BALO_23001_10,"跳转到账单详情页面为空");
    }
}
function crawl(){
    logger.info("浦发云账单 taskKey:{} 开始抓取",context.get(LUA_TASK_KEY));
    var acc_list = context.get("acc_card_list");
    logger.info("浦发云账单 taskKey:{} 抓取到{}张信用卡",context.get(LUA_TASK_KEY),acc_list.size());
    var month_list = context.get("month_list");
    logger.info("浦发云账单 taskKey:{} 抓取{},{}月账单",context.get(LUA_TASK_KEY),month_list,month_list.size());
    // 采集卡信息页面，获取卡号
    getCardListHtml();
    // 循环卡列表，获取客户号和当账单日
    for(var accIndex = 0 ;accIndex<acc_list.size();accIndex++){
        // 获取对应的creditCardAllData
        var creditCardAllData = new CreditCardAllData();
        dataList.add(creditCardAllData);
        var accSingle =acc_list.get(accIndex);
        billDay = accSingle.accDay;// 账单日
        context.put(accIndex + "_billDay",billDay);
        var accontNum = accSingle.accNo;//客户号
        // 解析卡号
        crawlCardListHtml(creditCardAllData);
        // 采集每一个账号的每一个月的已出账单数据
        for(var monthIndex = 0 ;monthIndex<month_list.size();monthIndex++){
            var bill = new BillAllData();
            // 采集每一个账号的每一个月信息
            var singleMonth = month_list.get(monthIndex);
            //采集每个月账单信息
            getAccMonthHtml(accIndex,accontNum,singleMonth,monthIndex);
            var pre_Bill_Detail = context.get(singleMonth+"pre_Bill_Detail");
            if(!equals("",pre_Bill_Detail) && null !== pre_Bill_Detail){
                // 抓取每一个账号的每一个月信息
                crawlAccMonthInfo(creditCardAllData,accIndex,bill,singleMonth);
                // 采集月账单详情信息
                getAccDateList(accIndex,accontNum,singleMonth);
                // 抓取月账单详情信息
                crawlAccDateList(bill,singleMonth);
                // 采集月账单详情
                getBillInfoHtml(accIndex,accontNum,singleMonth);
                // 抓取月账单总消费信息
                crawlBillInfoHtml(creditCardAllData,bill,singleMonth);
            }else {
                logger.info("浦发云账单，taskKey:{},{}月账单详情，pre_Bill_Detail 未获取到响应页面",context.get(LUA_TASK_KEY), billMonth);
                throw new BankException(BACR_20306_30,"消费明细获取失败");
            }
            creditCardAllData.getBills().add(bill);
        }
        // 采集未出账单信息
        getUnBillHtml(accIndex);
        // 解析未出账单数据信息
        var undoneBill = new BillAllData();
        var billMonth= simpleDateFormatToYear(0,"yyyy-MM","M",context.get(LUA_TASK_KEY));//未出账单一般为当月
        crawlUnBillInfo(creditCardAllData,undoneBill,billMonth,accIndex);
        creditCardAllData.getBills().add(undoneBill);
    }
    context.put(Constants.ALL_DATA,dataList)
}

/**
 * 为登录成功后选取卡和账单月
 */
function crawlCardList() {
    logger.info("浦发云账单 taskKey:{} 开始抓取信用卡卡信息",context.get(LUA_TASK_KEY));
    var login_html = context.get("login_html");
    var accList = new ArrayList();
    var monthList = new ArrayList();
    var accInfo = {};
    var accountInfoListHtml =  Jsoup.parse(login_html);
    var accountInfoList = accountInfoListHtml.select("#loginAccountHide option");
    var loginMonthList = accountInfoListHtml.select("#loginMonth option");
    for(var monthIndex = 1;monthIndex<loginMonthList.size();monthIndex++){
        var loginMonth = loginMonthList.get(monthIndex);
        var login_month = loginMonth.attr("value");
        monthList.add(login_month);
    }
    context.put("month_list",monthList);
    logger.info("浦发云账单 任务:{} 抓取到【{}】信用卡卡信息",context.get(LUA_TASK_KEY),accountInfoList.size() -1);
    for(var accIndex = 1;accIndex<accountInfoList.size();accIndex++){
        var accSing = accountInfoList[accIndex];
        //获取账单日
        var accDay = accSing.attr("value");
        //获取客户号
        var accNo = accSing.text();
        accInfo.accDay = accDay;
        accInfo.accNo = accNo;
        accList.add(accInfo);
    }
    logger.info("浦发云账单 任务:{} 卡列表accList：{}",context.get(LUA_TASK_KEY),accList);
    context.put("acc_card_list",accList)
    context.put("creditCardSize",accList.size());
}

/**
 * 获取用户的卡号
 */
function getCardListHtml() {
    //获取卡号列表信息
    var cardListUrl = urls.REQ_CARD_INFO_LIST_URL;
    var paramsMap = new HashMap();
    var cardListHTML= luaFuncs.pf_ajax_post(cardListUrl, paramsMap, timeout);
    storeDataToFile(context, cardListHTML,"spdCardList.html");
    context.put("card_list_html",cardListHTML);
}
function crawlCardListHtml(creditCardAllData) {
    var cardListHTML = context.get("card_list_html");
    var cardListMap = JSON.parse(cardListHTML);
    var cardList =  cardListMap.accountInfoList;
    if(cardList != null){
        if (cardList.size()>0){
            var full_card_num = cardList[0].cardNum.trim().replace(/\s/g,"");
            if(StringUtils.isNotBlank(full_card_num)){
                creditCardAllData.setFullCardNum(full_card_num);
                creditCardAllData.setCardNum(full_card_num.substring(full_card_num.length() - 4));
            }
        }
    }
    creditCardAllData.setOpenBank("浦发银行")
}
/**
 * 功能描述:初始化creditAllData的一些属性
 * @auther: SSD
 * @date: 2018/7/25 14:25
 */
function initCreditAllDataFun(creditCardAllData,accSingle) {
    logger.info("任务【{}】,浦发信用卡云账单，开始初始化creditCardAllData",context.get(LUA_TASK_KEY));
    try {
        var accontNo = accSingle.get("accNo");

        logger.info("任务【{}】,光大银行信用卡，初始化creditCardAllData完成",context.get(LUA_TASK_KEY));
    } catch (e) {
        logger.error("任务【{}】,光大银行信用卡，初始化creditCardAllData异常【{}】",context.get(LUA_TASK_KEY),e);
        statCaughtExceptionByJS(context, e);
    }
}

/**
 * 采集月账单信息
 */
function getAccMonthHtml(accIndex,accontNum,singleMonth,monthIndex) {
    var showPcIndexUrl = "" ;
    var askBillHtmlUrl = urls.REQ_LOGIN_INDEX_URL + "?accountId="+ accontNum +"&billYM="+ singleMonth;
    //循环抓取月份信息时，第一个月的请求跟其余月的请求稍有不同（请求参数不同,链接不同）故分开处理
    if(0 == monthIndex){
        logger.info("浦发云账单 taskKey:{} 第一个月账单信息请求即将发送",context.get(LUA_TASK_KEY));
        var billHtml = luaFuncs.pf_ajax_get(askBillHtmlUrl, timeout);
        storeDataToFile(context, billHtml, accIndex + "_"+"billHtml.html");
        if(billHtml.contains("return is null")){
            logger.info("浦发云账单 taskKey:{} ：第一个月账单页面响应为空",context.get(LUA_TASK_KEY),singleMonth);
        }
    }else{
        var changeAccountOrBillDataUrl = urls.REQ_ACCOUNT_OR_BILL_DATA_URL;
        var paramsMap = new HashMap();
        paramsMap.put("bilM", singleMonth);
        paramsMap.put("accountId", accontNum);
        var changeAccountOrBillDataHtml =luaFuncs.pf_ajax_post(changeAccountOrBillDataUrl, paramsMap, timeout);
        //辅助请求就是本请求可能不需要拿回数据，但是不发它接下来的请求会出错
        logger.info("浦发云账单，taskKey:{} 查询非第一个月的月账单表头时的辅助请求changeAccountOrBillDataUrl 已经发送！",context.get(LUA_TASK_KEY));
        storeDataToFile(context, changeAccountOrBillDataHtml, accIndex+"_changeAccountOrBillDataHtml_"+singleMonth+".html");
        if(!changeAccountOrBillDataHtml.contains("flag")){
            return;
        }
        showPcIndexUrl = urls.REQ_SHOW_PC_INDEX_URL;
        var showPcIndexHtml = luaFuncs.pf_ajax_get(showPcIndexUrl, timeout);
        logger.info("浦发云账单，taskKey:{} 查询非第一个月的月账单表头时的辅助请求showPcIndexUrl 已经发送！",context.get(LUA_TASK_KEY));
        storeDataToFile(context, showPcIndexHtml, accIndex+"_showPcIndexHtml_"+singleMonth+".html");
    }
    //如果发起下面的请求则需要有上面的请求作为铺垫，否则请求下面的数据是第一次请求的数据，注意
    var loadHomeDataUrl = urls.REQ_LOAD_HOME_DATA_URL;
    var billDataHtml = luaFuncs.pf_ajax_get(loadHomeDataUrl, timeout);
    // context.put("bill_data_html",billDataHtml);
    logger.info("浦发云账单，taskKey:{},月账单：{}主页面获取到即将保存！", context.get(LUA_TASK_KEY), singleMonth);
    storeDataToFile(context, billDataHtml, accIndex + "_" + singleMonth + "_DoneBill.html");
    if(StringUtils.isBlank(billDataHtml)){
        logger.info("浦发云账单，taskKey:{},月账单：{}主页为空",context.get(LUA_TASK_KEY),billMonth);
        throw new BankException(BALO_99601_40, "抓取月账单表头所需参数未获取到");
    }else if (billDataHtml.contains("Unable to process requested URL") || billDataHtml.contains("cross-domain fail")){
        logger.info("浦发云账单，taskKey:{},月账单：{}主页提示：Unable to process requested URL",context.get(LUA_TASK_KEY),billMonth);
        throw new BankException(BALO_21301_10, "Unable to process requested URL");
    }else if (billDataHtml.contains("return is null") ){
        logger.info("浦发云账单 taskKey:{} 月份：{} 主页返回为return is null",context.get(LUA_TASK_KEY),billMonth);
    }else if (billDataHtml.contains("9DhefwqGPrzGxEp9hPaoag") ){
        logger.info("浦发云账单 taskKey:{} 月份：{} 主页返回为页面元素中包含'9DhefwqGPrzGxEp9hPaoag'的空白页面",context.get(LUA_TASK_KEY),billMonth);
    }else if(StringUtils.isNotBlank(billDataHtml)){
        context.put(singleMonth+"bill_data_html",billDataHtml);
        //该请求是为接下来的账单详情做准备
        var preBillDetailDataUrl = urls.REQ_PC_BILL_DETAIL_URL;
        var preBillDetailDataHtml = luaFuncs.pf_ajax_get(preBillDetailDataUrl,timeout);
        context.put(singleMonth+"pre_Bill_Detail",preBillDetailDataHtml);
        logger.info("浦发云账单，taskKey:{},月账单：{} 账单详情！", context.get(LUA_TASK_KEY), singleMonth);
        storeDataToFile(context, preBillDetailDataHtml, accIndex + "_" + singleMonth + "_DoneBillDetail.html");
    }
}

/**
 *
 * @param accontNum
 * @param singleMonth
 */
function getAccDateList(accIndex,accontNum, singleMonth) {
    logger.info("浦发云账单，taskKey:{},采集：{}月，账单详情",context.get(LUA_TASK_KEY), singleMonth);
    //请求账单详情
    var billDetailUrl = urls.REQ_LOAD_BILLS_DETAILALL_URL;
    var paramsMap = new HashMap();
    paramsMap.put("month", singleMonth);
    paramsMap.put("rnd", Double.toString(Math.random()));
    paramsMap.put("sort", "0");
    var billDetailHtml = luaFuncs.pf_ajax_post(billDetailUrl, paramsMap, timeout);
    context.put(singleMonth +"bill_detail_html",billDetailHtml);
    storeDataToFile(context, billDetailHtml, accIndex +"_" + "bill_Done_"+singleMonth+"_shopping.html");
    logger.info("浦发云账单，taskKey:{},获取到：{}月，账单详情",context.get(LUA_TASK_KEY), singleMonth);
}

/**
 * 采集月账单还款总额，消费总额等
 * @param accIndex
 * @param accontNum
 * @param singleMonth
 */
function getBillInfoHtml(accIndex,accontNum,singleMonth) {
    logger.info("浦发云账单，taskKey:{},{} 月账单 getBillInfoHtml采集页面开始。",context.get(LUA_TASK_KEY), singleMonth);
    // 本期，上期还款信息，本期应还款总额= 上期应还款余额- 已还款金额/其他入账+ 新签金额/其他费用
    var PCloadHomeDataUrl = urls.REQ_PC_LOAD_HOME_DATA_URL;
    var PCloadHomeDataHtml = luaFuncs.pf_ajax_get(PCloadHomeDataUrl,timeout);
    logger.info("浦发云账单，taskKey:{},{} 月账单 PCloadHomeData请求已经发送。",context.get(LUA_TASK_KEY), singleMonth);
    context.put(singleMonth +"pc_load_home_data_html",PCloadHomeDataHtml);
    storeDataToFile(context, PCloadHomeDataHtml, accIndex + "_PCloadHomeData_"+singleMonth+".html");
    logger.info("浦发云账单，taskKey:{},{} 月账单 getBillInfoHtml采集页面结束。",context.get(LUA_TASK_KEY), singleMonth);
}

function crawlBillInfoHtml(creditCardAllData,bill,singleMonth) {
    logger.info("浦发云账单，taskKey:{},{} 月账单 crawlBillInfoHtml抓取开始。",context.get(LUA_TASK_KEY), singleMonth);
    var PCloadHomeDataHtml = context.get(singleMonth+"pc_load_home_data_html");
    if(PCloadHomeDataHtml.contains("Unable to process requested URL")|| PCloadHomeDataHtml.contains("return is null") || PCloadHomeDataHtml.contains("9DhefwqGPrzGxEp9hPaoag")){
        logger.info("浦发云账单，taskKey:{},{} 月账单 PCloadHomeData请求响应提示：未获取到数据直接退出",context.get(LUA_TASK_KEY), singleMonth);
        return;
    }
    try {
        var PCloadHomeData = JSON.parse(PCloadHomeDataHtml);
        if(null == PCloadHomeData || PCloadHomeData.size() <= 0 ){
            logger.info("浦发云账单，taskKey:{},{} 月账单 PCloadHomeData请求响应为空",context.get(LUA_TASK_KEY),singleMonth);
        }else{
            //解析
            var billData = PCloadHomeData.get("billData");
            var last_payments = billData.get("backMoney");   //已还款金额
            last_payments = ifNullSet0(last_payments);
            var lastPayments = stringToBigDecimal(last_payments);
            bill.setLastPayment(lastPayments.multiply(stringToBigDecimal("-1")));//把已还金额设置为负数

            var new_balance = billData.get("cash");          //本期应还总额
            new_balance = ifNullSet0(new_balance);
            var newBalance = stringToBigDecimal(new_balance);
            bill.setNewBalance(newBalance);

            var last_balance = billData.get("lastMoney");    //上期应还款余额
            last_balance = ifNullSet0(last_balance);
            var lastBalance = stringToBigDecimal(last_balance);
            bill.setLastBalance(lastBalance);

            //本期应还款总额 - 上期应还款余额  + 已还款金额/其他入账 = 新签金额/其他费用
            var new_charges = (newBalance.add(lastPayments)).subtract(lastBalance);
            bill.setNewCharges(new_charges);
        }

    } catch (e) {
        logger.error("浦发信用卡云账单 taskKey:{} crawlBillInfoHtml  方法发生异常：{}",context.get(LUA_TASK_KEY),e);
        statCaughtExceptionByJS(context, e);
    }
}
/**
 * 抓取已出账单详情信息
 */
function crawlAccDateList(bill,singleMonth) {
    logger.info("浦发云账单，taskKey:{},抓取到：{}月，账单详情",context.get(LUA_TASK_KEY), singleMonth);
    var billDetailHtml = context.get(singleMonth + "bill_detail_html");
    if(billDetailHtml.length() > 0 && !billDetailHtml.contains("return is null") && !billDetailHtml.contains("images/wl.png") && !StringUtils.equals(billDetailHtml,"") && !billDetailHtml.contains("9DhefwqGPrzGxEp9hPaoag")){
        var billDetailMap = JSON.parse(billDetailHtml);
        if(billDetailMap.size() > 0){
            var listDate = billDetailMap.get("billDataList");
            // logger.info("浦发云账单，listDate:{},", listDate);
            var list = listDate.get("billDataList");
            // logger.info("浦发云账单，list:{},", list);
            if(null !== list && list.size() > 0){
                var installmentList = new ArrayList();
                var orderIndex = 0;
                for each(var map in list){
                    orderIndex++;
                    getExpense(map, bill, "DONE", orderIndex,installmentList);
                }
                //处理分期数据
                manageInstallmentList(installmentList);
                // 分期中的手续费
                bill.setInstallments(installmentList);
            }
        }
    }else{
        logger.error("浦发云账单，taskKey:{},获取到：{}月，账单详情页面为空----网络错误",context.get(LUA_TASK_KEY), singleMonth)
    }

}

/**
 * 管理分期，把手续费或息费合并到分期账单中
 * @param installmentList
 */
function manageInstallmentList(installmentList) {
    // 遍历分期数据
    for(var insIndex = 0 ;insIndex < installmentList.size();insIndex++){
        var insInfo = installmentList.get(insIndex);
        var insInfoDesc = insInfo.getInstallmentDesc();
        if(insInfoDesc.contains("息费") || insInfoDesc.contains("手续费")){
            if(installmentList.size() > 0){
                for(var installIndex = 0;installIndex < installmentList.size();installIndex++){
                    var installInfo = installmentList.get(installIndex);
                    var installment_desc = installInfo.getInstallmentDesc();
                    var installmentDescText = installment_desc.substring(installment_desc.indexOf("第"),installment_desc.length());
                    // var install_currentMonth = installInfo.getCurrentMonth();
                    if (insInfoDesc.contains(installmentDescText)){
                        installInfo.setHandingfeeDesc(insInfoDesc);
                        installInfo.setHandingFee(insInfo.getAmountMoney());
                    }
                }
            }
            installmentList.remove(insIndex);
        }
    }
}
/**
 * 抓取月账单数据
 */
function crawlAccMonthInfo(creditCardAllData,accIndex,bill,singleMonth) {
    logger.info("浦发云账单，taskKey:{} crawlAccMonthInfo()方法，开始抓取第 {} 张信用卡 {} 月份账单数据",context.get(LUA_TASK_KEY),accIndex,singleMonth);
    var billDataHtml = context.get(singleMonth+"bill_data_html");
    //美元相关
    setValueForBillUSDCredit(bill);
    bill.setInterest(null);
    bill.setBillId(UUID.randomUUID().toString());
    bill.setBillType("DONE");
    bill.setBankName("浦发银行");
    try {
        if(billDataHtml.contains("return is null")){
            logger.error("浦发云账单 taskKey:{} 月份：{} billDataHtml页面响应为空",context.get(LUA_TASK_KEY),singleMonth);
        }else{
            //在月账单中为data中的几个字段赋值
            parseAccountDetailInfo(billDataHtml, creditCardAllData);
            var map = JSON.parse(billDataHtml);
            var userName = map.get("userName");
            //持卡人姓名
            userName = userName.replaceAll(" ","").replaceAll("先生","").replaceAll("女士","");
            creditCardAllData.setNameOnCard(userName);
            //预借现金额度
            var cash_limit = map.get("cashLimit").replaceAll("￥", "").replaceAll(",", "").trim();    //￥47,500.00
            creditCardAllData.setCashLimit(stringToBigDecimal(cash_limit));

            // 还款日
            var date = map.get("lastBackDate");
            if(null !== date && !equals("",date)){
                var payment_due_date = getDateStr(date, "yyyyMMdd","yyyy-MM-dd");
                bill.setPaymentDueDate(getDate(payment_due_date,"yyyy-MM-dd"));
            }
            // 账单日
            var billMonth1 = map.get("billMonth");  //201712
            billDay = context.get(accIndex + "_billDay");
            var billDateTime = billMonth1 + billDay;
            var date1 = billMonth1 + String.valueOf(billDay);
            if(null !== billDateTime && !equals("",billDateTime)){
                var bill_date = getDateStr(billDateTime, "yyyyMMdd","yyyy-MM-dd");
                bill.setBillDate(getDate(bill_date,"yyyy-MM-dd"));//账单日
            }
            //账单月份
            var date2 = map.get("billMonth");
            if(null !== date2 && !equals("",date2)){
                var bill_month1 = getDateStr(date2, "yyyyMM","yyyy-MM");
                bill.setBillMonth(bill_month1);//账单月份
            }
            //本期账单金额
            var new_balance = map.get("cash").replaceAll(",", "").trim();
            if(null !== new_balance && !equals("",new_balance)){
                bill.setNewBalance(stringToBigDecimal(new_balance));stringToBigDecimal(new_balance);
            }
            //最低还款额
            var min_payment = map.get("minPay").replaceAll(",", "").trim();
            if(null !== min_payment && !equals("",min_payment)){
                bill.setMinPayment(stringToBigDecimal(min_payment));
            }
            //信用卡额度
            var credit_limit = map.get("creditLimit").replaceAll(",", "").replaceAll("￥", "").trim();
            if(null !== credit_limit && !equals("",credit_limit)){
                bill.setCreditLimit(stringToBigDecimal(credit_limit));
                bill.setNewCharges(stringToBigDecimal(credit_limit));
            }
            bill.setCashLimit(stringToBigDecimal(cash_limit));
        }
    } catch (e) {
        logger.info("浦发云账单，taskKey:{} parseBillData()方法 月份：{} 发生异常：{}",context.get(LUA_TASK_KEY),singleMonth , e);
        statCaughtExceptionByJS(context, e);
    }
}

/**
 * 在月账单中为data中的几个字段赋值
 */
function parseAccountDetailInfo(billDataHtml, data){
    try {
        data.setCardId(UUID.randomUUID().toString());
        data.setCardType("信用卡");
        data.setBankName("浦发银行");
        data.setCashBalance(null);
        if(StringUtils.isNotBlank(billDataHtml)){
            var billData = JSON.parse(billDataHtml);
            var credit_limit = billData.get("creditLimit").trim().replaceAll(",","").replaceAll("￥","");
            data.setCreditLimit(stringToBigDecimal(credit_limit));
            var balance = billData.get("creditLimit").trim().replaceAll(",","").replaceAll("￥","");
            data.setBalance(stringToBigDecimal(balance));
            // var full_card_num = billData.cardNo.trim().replace(/\s/g,"");//去除所有空格   张振伟修改
            // data.setFullCardNum(full_card_num);
            // data.setCardNum(full_card_num.substring(full_card_num.length() - 4));
        }
    } catch (e) {
        logger.error("浦发云账单 taskKey:{} parseAccountDetailInfo()方法中解析基本信息异常：{}",context.get(LUA_TASK_KEY),e);
        statCaughtExceptionByJS(context, e);
    }
}
/**
 * 与美元相关
 * @param billAllData
 */
function setValueForBillUSDCredit(billAllData){
    billAllData.setUsdNewBalance(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setUsdCashLimit(null);
}

/**
 * 采集未出账单消费信息
 * @param accIndex
 */
function getUnBillHtml(accIndex) {
    //请求未出账单详情
    var unDoneBillDetailUrl = urls.REQ_SHOW_UNBILL_DETAIL_URL;
    var unDoneBillDetail = luaFuncs.pf_ajax_get(unDoneBillDetailUrl,timeout);
    logger.info("浦发云账单，taskKey:{},获取到：{}月，未出账单详情",context.get(LUA_TASK_KEY));
    storeDataToFile(context, unDoneBillDetail, accIndex +"_"+ "bill_unDone_shopping.html");
    context.put(accIndex + "_undone_bill_detail",unDoneBillDetail);
}

/**
 * 抓取未出账单数据
 */
function crawlUnBillInfo(creditCardAllData,undoneBill,billMonth,accIndex) {
    var unDoneBillDetail = context.get(accIndex + "_undone_bill_detail");
    undoneBill.setBillId(UUID.randomUUID().toString());
    undoneBill.setBankName("浦发银行");
    undoneBill.setBillType("UNDONE");
    undoneBill.setBillMonth(getDateStr(billMonth, "yyyyMM", "yyyy-MM"));
    // var unBillDay = context.get(accIndex + "_billDay");
    undoneBill.setBillDate(getDate(billMonth + billDay, "yyyyMMdd"));
    //美元相关
    setValueForBillUSDCredit(undoneBill);
    if(StringUtils.isNotBlank(unDoneBillDetail) && !unDoneBillDetail.contains("return is null") ){
        var billDetailMap = JSON.parse(unDoneBillDetail);
        if(billDetailMap.size() > 0){
            var listDate = billDetailMap.get("billDetaillist");
            var list = listDate.get("billDataList");
            if(null !== list && list.size() > 0){
                var installmentList = new ArrayList();
                var orderIndex = 0;
                for each(var map in list){
                    orderIndex++;
                    getExpense(map, undoneBill, "UNDONE", orderIndex,installmentList);
                }
                manageInstallmentList(installmentList);
                undoneBill.setInstallments(installmentList);
            }
        }
    }else{
        logger.error("浦发云账单， taskKey:{} 获取到：{}月，未出账单详情 为空 ----网络异常 ",context.get(LUA_TASK_KEY), bill.getBillMonth());
    }
}
/**
 * 保存消费详情
 * @param map
 * @param bill
 * @param billType   --unDone  or done
 */
function getExpense(map, bill, billType, orderIndex,installmentList){
    try {
        var expense = new Expense();
        var uuid = UUID.randomUUID().toString();
        bill.getShoppingSheets().add(expense);
        expense.setId(uuid);
        expense.setBalance(null);
        expense.setCurrencyType("CNY");
        expense.setOrderIndex(orderIndex);

        //页面上  cardNbr1 参数为卡号
        var full_card_num = map.get("cardNbr1");
        expense.setCardNum(full_card_num.substring(full_card_num.length()-4));
        //页面上将本条消费详情的描述分为两部分表示 desLine1 和 desLine2 我们需要将他们组合起来作为我们的描述字段
        var description = map.get("desLine1");
        var description1 = map.get("desLine2");
        if(!equals("",description1)){
            description = description+description1;
        }
        expense.setDescription(description);
        var valDate = map.get("valDate");
        // var tansMonth = getDateStr(valDate, "yyyyMMdd", "yyyy-MM")
        expense.setPostDate(getDate(valDate, "yyyyMMdd"));
        // expense.setPostDate(yyyy_MM_dd_PARSER.parse(getDateStr(valDate, "yyyyMMdd"), "yyyy-MM-dd")));
        var purDate8 = map.get("purDate8");
        expense.setTransDate(getDate(purDate8, "yyyyMMdd"));

        var cunOrQu = map.get("amountFl");
        var amm = map.amount.replaceAll(",", "").trim();
        var amountMoney = stringToBigDecimal(amm);
        if(equals("DONE",billType)){
            if(equals("C",cunOrQu)){
                expense.setAmountMoney(amountMoney.multiply(stringToBigDecimal("-1")));
            }else if(equals("D",cunOrQu)){
                expense.setAmountMoney(amountMoney);
            }
        }else if(equals("UNDONE",billType)){
            if(equals("-",cunOrQu)){
                expense.setAmountMoney(amountMoney.multiply(stringToBigDecimal("-1")));

                var new_balance = bill.getNewBalance();
                logger.info("new_balance = " + context.get(LUA_TASK_KEY) +" "+ new_balance);
                logger.info("null == new_balance  ？:{}" , (new_balance == null || equals("",new_balance)));
                if(new_balance == null  || equals("",new_balance)){
                    new_balance = stringToBigDecimal("0");
                }
                logger.info("new_balance = " + context.get(LUA_TASK_KEY) +" "+ new_balance);
                bill.setNewBalance(new_balance.add(amountMoney.multiply(stringToBigDecimal("-1"))));

            }else if(equals("+",cunOrQu)){
                expense.setAmountMoney(amountMoney);
                var new_balance = bill.getNewBalance();
                if(new_balance == null || equals("",new_balance)){
                    new_balance = stringToBigDecimal("0");
                }

                bill.setNewBalance(new_balance.add(amountMoney));

                var new_charges = bill.getNewCharges();
                if(new_charges == null  || equals("",new_charges)){
                    new_charges = stringToBigDecimal("0");
                }
                bill.setNewCharges(new_charges);
            }
        }
        expense.setCategory(classify(description, amountMoney));
        // if(description.contains("第")&&description.contains("期")&&description.contains("共")){
        //     expense.setCategory("INSTALLMENT");
        // }else if(description.contains("消费")){
        //     expense.setCategory("SHOPPING");
        // }else if(description.contains("转分期付款")){
        //     expense.setCategory("PAYMENTS");
        // }else{
        //     expense.setCategory(CategoryUtil.getCreditCategory("SPD", description, amountMoney));
        // }
        //处理账单分期数据
        if((description.contains("第") && description.contains("期共")) || description.contains("分期")){
            var installment = new Installment();
            // bill.getInstallments().add(installment);
            installment.setBillId(UUID.randomUUID().toString());
            installment.setAmountMoney(expense.getAmountMoney());
            installment.setCurrencyType("CNY");
            installment.setInstallmentDesc(description);
            installment.setShoppingsheetId(uuid);
            if(description.contains("第") && description.contains("期共")){
                var descText = description.substring(description.indexOf("第"),description.length());
                //installment.setTransDate(expense.getTransDate());
                var current_month = descText.substring(descText.indexOf("第") + 1, descText.indexOf("期"));
                var total_month = descText.substring(descText.indexOf("共") + 1, descText.lastIndexOf("期"));
                var transDate = getTimeMonthToNumMonth(Integer.toString(current_month),valDate);
                installment.setTransDate(transDate);
                var purDates = getTimeMonthToNumMonth(0,purDate8);//记账日期
                installment.setPostDate(purDates);
                installment.setInstallmentType(installmentTypeChange(description));
                //这里需要对description进行截取，当description包含现金分期，以前的方法会报错
                installment.setCurrentMonth(current_month);//当前期数
                installment.setTotalMonth(total_month);//总共期数
            }
            installmentList.add(installment);
        }
    } catch (e) {
        logger.info("浦发云账单taskKey:{} 在解析 {}月{}账单数据时出错",context.get(LUA_TASK_KEY),bill.getBillMonth(),billType);
        statCaughtExceptionByJS(context, e);
    }
}
/**
 * 判断字符串中是否包含字母 （用于判断分期数据的条件中）
 * @param str
 * @return
 */
function checkIfContainsNum(str) {
    var isDigit = false;
    if(str.matches(".*\\d+.*")){
        isDigit = true;
    }
    return isDigit;
}
/**
 * 几个金额字段，如果从页面取下值为 null 那么为其赋值为 0
 */
function ifNullSet0(amount){
    if(null == amount || equals("",amount) || typeof amount == "undefined"){
        amount = "0";
    }else{
        amount = amount.trim().replaceAll(",", "").replaceAll("￥", "");
    }
    return amount;
}
function inputIdCard(idNo) {
    //输入身份证号
    if(StringUtils.isNotBlank(idNo)){
        var isInputIdNo = set_input_text_by_id("idNo",idNo);
        logger.info("任务【 {} 】验证身份号:{},是否输入:{}",context.get(LUA_TASK_KEY),idNo, isInputIdNo);
        if(equals(isInputIdNo.toLowerCase(),"ok")){
            isInput = true;
        }
    }
    // var idNoInputResult = luaFuncs.checkIfInput("idNo",idNo);
    var isIdNoInputCorrectFunc = function(isInput) {
        return isInput;
    }
    var getIdNoInputErrorMsgFunc = function() {
        return "身份证号未输入";
    }
    assertTrueOrThrowException(isInput, isIdNoInputCorrectFunc, getIdNoInputErrorMsgFunc);
    logger.info("任务【 {} 】身份证号输入成功", context.get(LUA_TASK_KEY));
}
/**
 * 获取图片验证码
 */
function getImgValidCode() {
    //获取图片验证码路径
    var captchaPath = get_image_by_id("imgObj");
    logger.info("任务【 {} 】图片验证码路径【 {} 】", context.get(LUA_TASK_KEY), captchaPath);
    var captchaPathState = true;
    if(captchaPath == null && typeof captchaPath == 'undefined' && captchaPath == 'path fail'){
        captchaPathState = false;
    }
    var isCaptchaPathCorrectFunc = function(captchaPathState) {
        return captchaPathState
    }
    var getCaptchaPathErrorMsgFunc = function() {
        return "图片验证码获取失败"
    }
    assertTrueOrThrowException(captchaPath, isCaptchaPathCorrectFunc, getCaptchaPathErrorMsgFunc)
    logger.info("任务【 {} 】图片验证码获取成功", context.get(LUA_TASK_KEY))
    //识别图片验证码
    context.put(TASK_IMG_PATH, captchaPath);
}
/**
 * 输入图片验证码
 */
function inputImgValidCode() {
//图片验证码只会是4位，但是由于官网返回经常有看不清的字母所以本处支持3,4位
    context.put(TASK_IMG_REGEX,"[0-9a-zA-Z]{4}");
    var captcha = waitImgCodeBySecondsByJs(context,60,true,3);
    logger.info("图片验证码为：{}",captcha);
    if (StringUtils.isBlank(captcha) || captcha.length() < 4) {
        logger.info("浦发云账单 任务taskKey:{} 验证码信息：打码位数不足四位，手动补足 {}", context.get(LUA_TASK_KEY),captcha);
        captcha = "1234";
    }
    //输入图片验证码
    set_input_text_by_id("code", captcha);
    return captcha;
}
/**
 * 获取该日期前后几年的日期
 * @param date  默认是当前时间
 * @param intYear
 */
function simpleDateFormatToYear(intYear,formatType,yearOrMothe) {
    var simpleDateFormat = new SimpleDateFormat(formatType);
    var calendar = Calendar.getInstance();
    var nowDate = calendar.getTime();
    if(equals("y",yearOrMothe)){
        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - intYear);
        nowDate =simpleDateFormat.format(calendar.getTime());
        logger.info("{浦发银行借记卡账单查询，获取今天的时间，{}",nowDate);
    }else if(equals("M",yearOrMothe)){
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - intYear);
        nowDate =simpleDateFormat.format(calendar.getTime());
        logger.info("{浦发银行借记卡账单查询，获取{}月的时间，",nowDate);
    }
    return nowDate;
}

/**
 *  获取前后N各月的当天时间
 * @param num 前后几个月
 * @param time 需要转换的时间
 * @returns {*}
 */
function getTimeMonthToNumMonth(num, time) {
    var calendar=Calendar.getInstance()
    var df=new SimpleDateFormat("yyyyMMdd");
    var years = time.substring(0,4);
    var month = time.substring(4,6);
    var day = time.substring(6,8);
    calendar.set(years, month, day);
    calendar.set(Calendar.MONTH,month-1-num);//默认1月为0月
    var nowTime = calendar.getTime();
    // logger.info("浦发云账单,的记账日期为：{}",df.format(nowTime));
    return nowTime;
}
/**
 * 调用验证错误提示公用方法
 * @param isValidFlag
 * @param errorDec
 * @param teskKey
 */
function isValidThorwError(isValidFlag, errorDec) {
    var isSmsCodeCorrectFunc = function() {
        return isValidFlag;
    }

    var getSmsCodeErrorMsgFunc = function() {
        return errorDec;
    }

    assertTrueOrThrowException(isValidFlag, isSmsCodeCorrectFunc, getSmsCodeErrorMsgFunc)
}

var luaFuncs = {
    /**
     * 获取当前页面信息
     * @returns {*}
     */
    getHtml2:function () {
        var map = new HashMap();
        map.put("method","getHtml2");
        return sendAndReceive(map);
    },
    /**
     *
     * @returns {*}
     */
    click_login_button: function(){
        var map = new LinkedHashMap();
        map.put("method", "click_login_button");
        return sendAndReceive(map);
    },
    /**
     * 选取卡
     * @returns {*}
     */
    selectAccount : function(){
        var map = new LinkedHashMap();
        map.put("method", "selectAccount");
        return sendAndReceive(map);
    },
    /**
     * 选取账单月
     * @param i
     * @returns {*}
     */
    selectBillMonth : function(i){
        var map = new LinkedHashMap();
        map.put("method", "selectBillMonth");
        map.put("index", i);
        return sendAndReceive(map);
    },
    /**
     *
     * @returns {*}
     */
    jumpToBill : function(){
        var map = new LinkedHashMap();
        map.put("method", "jumpToBill");
        return sendAndReceive(map);
    },
    /**
     * get请求
     * @param url
     * @param outtime
     * @returns {*}
     */
    pf_ajax_get: function(url, outtime){
        var map = new LinkedHashMap();
        map.put("method", "ajax_get");
        map.put("url", url);
        map.put("timeout", outtime);
        return sendAndReceive(map);
    },
    /**
     * post请求
     * @param url
     * @param postdata
     * @param outtime
     * @returns {*}
     */
    pf_ajax_post: function( url, postdata, outtime) {
        var map = new LinkedHashMap();
        var sb = new StringBuffer();
        for each(var key in postdata.keySet()) {
            sb.append(key + "=" + postdata.get(key) + "&");
        }
        var data = "";
        if (sb.length() > 0) {
            data = sb.substring(0, sb.length() - 1);
        }
        map.put("method", "ajax_post");
        map.put("url", url);
        map.put("data", data);
        map.put("timeout", outtime);
        return sendAndReceive(map);
    },
    /**
     * 关闭选取账单月和账号时的错误提示
     * @returns {*}
     */
    closeErrorMsgButton : function(){
        var map = new LinkedHashMap();
        map.put("method", "closeErrorMsgButton");
        return sendAndReceive(map);
    },
    setSizeAndShow : function(){
        var map = new LinkedHashMap();
        map.put("method", "setSizeAndShow");
        return sendAndReceive(map);
    },
    //检查用户名，验证码，密码是否输入正常（参数1：id, 参数2：正确的值）
    checkIfInput : function(id,value){
        var map = new LinkedHashMap();
        map.put("method", "checkIfInput");
        map.put("id", id);
        map.put("value", value);
        return sendAndReceive(map);
    },
    faindCardlist : function(id,value){
        var map = new LinkedHashMap();
        map.put("method", "faindCardlist");
        return sendAndReceive(map);
    },
    threadSleep : function(){
        var map = new LinkedHashMap();
        map.put("method", "threadSleep");
        return sendAndReceive(map);
    },
}